package com.szewec.ps.ui.common;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ZoomControls;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.szewec.ps.R;
import com.szewec.ps.base.Constants;
import com.szewec.ps.databinding.ActivityLocationEditBinding;
import com.szewec.ps.model.selectmappoint.SelectedPoint;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class LocationEditActivity extends AppCompatActivity {
    private ActivityLocationEditBinding binding;
    private static final String TAG = "LocationEditActivity";
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private BDLocation bdlocation;
    //是否第一次定位
    private boolean isFirstLocate = true;
    private GeoCoder mCoder;
    //当前地图中心点坐标
    private LatLng centerPoint;
    //地址
    private String currentAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_location_edit);
        ButterKnife.bind(this);
        initMap();
    }
    private void initMap(){
        // 隐藏百度的LOGO
        mMapView = binding.bmapView;
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.GONE);
        }
        // 不显示地图上比例尺
        mMapView.showScaleControl(false);
        // 不显示地图缩放控件（按钮控制栏）
        mMapView.showZoomControls(false);

        mBaiduMap = mMapView.getMap();
        //开启地图的定位图层
        mBaiduMap.setMyLocationEnabled(true);

        //通过LocationClient发起定位
        //定位初始化
        mLocationClient = new LocationClient(this);


        //通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);

        //设置locationClientOption
        mLocationClient.setLocOption(option);

        //注册LocationListener监听器
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        //开启地图定位图层
        mLocationClient.start();
        //手势
        UiSettings settings = mBaiduMap.getUiSettings();
        settings.setOverlookingGesturesEnabled(false);//屏蔽双指下拉时变成3D地图
        settings.setRotateGesturesEnabled(false);//屏蔽旋转

        //坐标转地址
        mCoder = GeoCoder.newInstance();
        mCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                if (reverseGeoCodeResult != null){
                    binding.tvAddress.setText(reverseGeoCodeResult.getAddress());
                    currentAddress = reverseGeoCodeResult.getAddress();
                }
            }
        });


        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                centerPoint = mapStatus.target;
                mCoder.reverseGeoCode(new ReverseGeoCodeOption().location(mapStatus.target).radius(100));
            }
        });
    }

    @OnClick({R.id.iv_back,R.id.tv_select_btn,R.id.iv_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_select_btn:
                if (centerPoint != null){
                    SelectedPoint point = new SelectedPoint();
                    point.setxCoordinate(centerPoint.longitude);
                    point.setyCoordinate(centerPoint.latitude);
                    point.setAddress(currentAddress);
                    Intent intent = new Intent();
                    intent.putExtra(Constants.EXTRA_KEY.MAP_CENTER_POINT,point);
                    //设置返回
                    setResult(Constants.RESULT_CODE.SELECTED_POINT,intent);
                }
                finish();
                break;
            case R.id.iv_location:
                //回到我的位置
                navigateTo(bdlocation, 19f);
                break;
        }
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            bdlocation = location;
            navigateToLocation(location);
        }
    }
    public void navigateToLocation(BDLocation location) {
        if (isFirstLocate){
            MyLocationData.Builder locationBuilder =
                    new MyLocationData.Builder();
            locationBuilder.latitude(location.getLatitude());
            locationBuilder.longitude(location.getLongitude());
            MyLocationData locationData = locationBuilder.build();
            mBaiduMap.setMyLocationData(locationData);
            //初次进入界面定位本地
            navigateTo(location, 19f);
        }
    }
    /**
     * 移动到指定位置
     *
     * @param location
     * @param v
     */
    public void navigateTo(BDLocation location, float v) {
        LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
        MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
        mBaiduMap.animateMapStatus(update);
        update = MapStatusUpdateFactory.zoomTo(v);//设置比例
        mBaiduMap.animateMapStatus(update);
        /*判断baiduMap是已经移动到指定位置*/
        if (mBaiduMap.getLocationData() != null)
            if (mBaiduMap.getLocationData().latitude == location.getLatitude()
                    && mBaiduMap.getLocationData().longitude == location.getLongitude()) {
                isFirstLocate = false;
            }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCoder.destroy();
    }
}
